package com.xnyzc.lhy.order.service.impl.driver;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.global.Configuration;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.cms.EVehicleType;
import com.xnyzc.lhy.common.penum.driver.info.EOaDUserDriverType;
import com.xnyzc.lhy.common.penum.user.EOaCUserEmailStatus;
import com.xnyzc.lhy.common.penum.user.EOaCUserIdentityVerfied;
import com.xnyzc.lhy.common.penum.user.EOaCUserIsBlocked;
import com.xnyzc.lhy.common.penum.user.EOaCUserSex;
import com.xnyzc.lhy.common.penum.user.info.EOaCUserInfoAgreement;
import com.xnyzc.lhy.common.penum.user.info.EOacUserInfoAuditType;
import com.xnyzc.lhy.common.penum.user.info.EOacUserInfoIdentityType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.order.entity.area.OaSysArea;
import com.xnyzc.lhy.order.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.order.entity.driver.wallet.OaDWallet;
import com.xnyzc.lhy.order.entity.result.cms.driver.CmsOaDUserImport;
import com.xnyzc.lhy.order.entity.result.user.UserLoginResult;
import com.xnyzc.lhy.order.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.order.entity.system.OaSysUser;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.order.entity.user.OaDUserOffice;
import com.xnyzc.lhy.order.entity.vehicle.OaDDriverVehicle;
import com.xnyzc.lhy.order.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.order.entity.vehicle.OaSysVehicleMdict;
import com.xnyzc.lhy.order.feign.amap.IAmapService;
import com.xnyzc.lhy.order.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.order.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.order.mapper.driver.wallet.OaDWalletMapper;
import com.xnyzc.lhy.order.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserOfficeMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaDDriverVehicleMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaSysVehicleMdictMapper;
import com.xnyzc.lhy.order.service.cms.driver.ICmsOaDUserImportService;
import com.xnyzc.lhy.order.service.driver.IOaDUserInfoService;
import com.xnyzc.lhy.order.service.driver.wallet.IOaDWalletService;
import com.xnyzc.lhy.order.service.system.IOaSysVehicleService;
import com.xnyzc.lhy.order.service.user.IOaDUserOfficeService;
import com.xnyzc.lhy.order.service.user.IOaDUserService;
import com.xnyzc.lhy.resource.entity.amap.AmapTidParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Description
 * @Author zhuyubin
 * @Date 2019-08-29 00:49
 **/
@Service
public class CmsOaDUserImportServiceImpl implements ICmsOaDUserImportService {

    @Autowired
    private IOaDUserService iOaDUserService;
    @Autowired
    private IOaDWalletService iOaDWalletService;
    @Autowired
    private IOaDUserOfficeService iOaDUserOfficeService;
    @Autowired
    private IOaDUserInfoService iOaDUserInfoService;
    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;
    @Autowired
    private OaSysGlobalConfigMapper oaSysGlobalConfigMapper;
    @Autowired
    private IOaSysVehicleService iOaSysVehicleService;
    @Autowired
    private IAmapService amapService;
    @Autowired
    private OaSysVehicleMdictMapper oaSysVehicleMdictMapper;
    @Autowired
    private OaSysDictMapper oaSysDictMapper;
    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;
    @Autowired
    private OaDDriverVehicleMapper oaDDriverVehicleMapper;
    @Autowired
    private OaSysUserMapper oaSysUserMapper;
    @Autowired
    private OaDUserOfficeMapper oaDUserOfficeMapper;
    @Autowired
    private OaDUserMapper oaDUserMapper;
    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;
    @Autowired
    private OaDWalletMapper oaDWalletMapper;
    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;
    @Autowired
    private IAmapService iAmapService;
    /**
     * 导入
     *
     * @param sysUserId            后台用户
     * @param tag                  租户
     * @param cmsOaDUserImportList 表格数据
     * @return
     */
    @Override
    public String userImport(Long sysUserId, String tag, String clientId, List<CmsOaDUserImport> cmsOaDUserImportList) {
        // 获取猎鹰服务id
        List<OaSysGlobalConfig> oaSysGlobalConfigs = oaSysGlobalConfigMapper.selectList(Wrappers.<OaSysGlobalConfig>lambdaQuery().eq(OaSysGlobalConfig::getTag, tag));
        Long sid = null;
        if (oaSysGlobalConfigs.size() == 1) {
            sid = oaSysGlobalConfigs.get(0).getGouldServiceId();
        }
        Date date = new Date();
        Map<String, Integer> phoneMap = new HashMap<>();
        Map<String, Integer> vehNoMap = new HashMap<>();
        Map<String, Integer> vehFrameNumberMap = new HashMap<>();
        Map<String, Integer> identityNumberMap = new HashMap<>();
        Map<String, Integer> formatPhoneMap = new HashMap<>();
        Map<String, Integer> formatVehNoMap = new HashMap<>();
        Map<String, Integer> formatFrameMap = new HashMap<>();
        Map<String, Integer> formatIdentityMap = new HashMap<>();
        List<OaDUser> oaDUserList = new ArrayList<>();
        List<OaDUserOffice> oaDUserOfficeList = new ArrayList<>();
        List<OaDUserInfo> oaDUserInfoList = new ArrayList<>();
        List<OaDWallet> oaDWalletList = new ArrayList<>();
        List<OaSysVehicle> oaSysVehiclesList = new ArrayList<>();
        // 查重
        List<OaDUser> oaDUsers = iOaDUserService.list(Wrappers.<OaDUser>lambdaQuery().eq(OaDUser::getTag, tag));
        List<OaSysVehicle> oaSysVehicles = iOaSysVehicleService.list(Wrappers.<OaSysVehicle>lambdaQuery().eq(OaSysVehicle::getTag, tag));
        List<OaDUserInfo> oaDUserInfos = iOaDUserInfoService.list(Wrappers.<OaDUserInfo>lambdaQuery().eq(OaDUserInfo::getTag, tag));
        // 对比数据库重复手机号
        StringBuffer repeatPhone = new StringBuffer();
        boolean isRepeatPhone = false;
        repeatPhone.append(MessageConstant.REPEAT_PHONE).append(":");
        // 对比数据库重复车牌号
        StringBuffer repeatVehNo = new StringBuffer();
        boolean isRepeatVehNo = false;
        repeatVehNo.append(MessageConstant.REPEAT_VEHICLE_NO).append(":");
        // 对比数据库重复车架号
        StringBuffer repeatVehFrame = new StringBuffer();
        boolean isRepeatVehFrame = false;
        repeatVehFrame.append(MessageConstant.REPEAT_VEHICLE_FRAME).append(":");
        // 对比数据库重复身份证号
        StringBuffer repeatIdentity = new StringBuffer();
        boolean isRepeatIdentity = false;
        repeatIdentity.append(MessageConstant.REPEAT_IDENTITY).append(":");
        StringBuffer formatPhone = new StringBuffer();
        boolean isFormatPhone = false;
        formatPhone.append(MessageConstant.FORMAT_PHONE).append(":");
        StringBuffer formatVehNo = new StringBuffer();
        boolean isFormatVehNo = false;
        formatVehNo.append(MessageConstant.FORMAT_VEHNO).append(":");
        StringBuffer formatVehFrame = new StringBuffer();
        boolean isFormatVehFrame = false;
        formatVehFrame.append(MessageConstant.FORMAT_VEHFRAME).append(":");
        StringBuffer formatIdentity = new StringBuffer();
        boolean isFormatIdentity = false;
        formatIdentity.append(MessageConstant.FORMAT_IDENTITY).append(":");
        boolean isRepeatArea = false;
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "vegicle_color_type");
        List<OaSysDict> dictList = oaSysDictMapper.selectList(queryWrapper);
        List<OaSysArea> areaList = oaSysAreaMapper.selectList(null);
        // 全部机构
        List<OaSysOffice> offices = oaSysOfficeMapper.selectList(Wrappers.<OaSysOffice>lambdaQuery().eq(OaSysOffice::getTag, tag));
        for (CmsOaDUserImport cmsOaDUserImport : cmsOaDUserImportList) {
            // 校验
            verify(phoneMap, vehNoMap, vehFrameNumberMap, identityNumberMap, cmsOaDUserImport);
            // 去空格
            cmsOaDUserImport.setDriverName(cmsOaDUserImport.getDriverName().replaceAll(" ", ""));
            cmsOaDUserImport.setDriverPhone(cmsOaDUserImport.getDriverPhone().replaceAll(" ", ""));
            cmsOaDUserImport.setIdentityNumber(cmsOaDUserImport.getIdentityNumber().replaceAll(" ", ""));
            cmsOaDUserImport.setDriverCityName(cmsOaDUserImport.getDriverCityName().replaceAll(" ", ""));
            cmsOaDUserImport.setVehNo(cmsOaDUserImport.getVehNo().replaceAll(" ", ""));
            cmsOaDUserImport.setVehFrameNumber(cmsOaDUserImport.getVehFrameNumber().replaceAll(" ", ""));
            cmsOaDUserImport.setVehEngineNumber(cmsOaDUserImport.getVehEngineNumber().replaceAll(" ", ""));
            cmsOaDUserImport.setVehCityName(cmsOaDUserImport.getVehCityName().replaceAll(" ", ""));
            //验证车架号
//            Pattern frameNumberPattern = Pattern.compile(Configuration.FRAME_REGULAR);
//            boolean frameNumber = Pattern.matches(frameNumberPattern.pattern(), String.valueOf(cmsOaDUserImport.getVehFrameNumber()));
//            if (!frameNumber) {
//                formatFrameMap.put(cmsOaDUserImport.getVehFrameNumber(), 1);
//                isFormatVehFrame = true;
//                formatVehFrame.append(cmsOaDUserImport.getVehFrameNumber()).append("、");
//            }
            //验证手机号
            Pattern phoneNumberPattern = Pattern.compile(Configuration.PHONE_REGULAR);
            boolean phoneNumber = Pattern.matches(phoneNumberPattern.pattern(), String.valueOf(cmsOaDUserImport.getDriverPhone()));
            if (!phoneNumber) {
                formatPhoneMap.put(cmsOaDUserImport.getDriverPhone(), 1);
                isFormatPhone = true;
                formatPhone.append(cmsOaDUserImport.getDriverPhone()).append("、");
            }
            //验证车牌号
            Pattern vehNoPatternOne = Pattern.compile(Configuration.VEH_NO_REGULAR);
            Pattern vehNoPatternTwo = Pattern.compile(Configuration.VEH_REGULAR);
            boolean vehNoValidationOne = Pattern.matches(vehNoPatternOne.pattern(), String.valueOf(cmsOaDUserImport.getVehNo()));
            boolean vehNoValidationTwo = Pattern.matches(vehNoPatternTwo.pattern(), String.valueOf(cmsOaDUserImport.getVehNo()));
            if (!vehNoValidationOne && !vehNoValidationTwo) {
                formatVehNoMap.put(cmsOaDUserImport.getVehNo(), 1);
                isFormatVehNo = true;
                formatVehNo.append(cmsOaDUserImport.getVehNo()).append("、");
            }
            //验证身份证号码
            Pattern identityPattern = Pattern.compile(Configuration.IDENTITY_REGULAR);
            boolean identityNumber = Pattern.matches(identityPattern.pattern(), String.valueOf(cmsOaDUserImport.getIdentityNumber()));
            if (!identityNumber) {
                formatIdentityMap.put(cmsOaDUserImport.getIdentityNumber(), 1);
                isFormatIdentity = true;
                formatIdentity.append(cmsOaDUserImport.getIdentityNumber()).append("、");
            }
            phoneMap.put(cmsOaDUserImport.getDriverPhone(), 1);
            vehNoMap.put(cmsOaDUserImport.getVehNo(), 1);
            vehFrameNumberMap.put(cmsOaDUserImport.getVehFrameNumber(), 1);
            identityNumberMap.put(cmsOaDUserImport.getIdentityNumber(), 1);
            for (OaDUser oaDUser : oaDUsers) {
                if (cmsOaDUserImport.getDriverPhone().equals(oaDUser.getDriverPhone())) {
                    isRepeatPhone = true;
                    repeatPhone.append(cmsOaDUserImport.getDriverPhone()).append("、");
                    break;
                }
            }
            for (OaDUserInfo info : oaDUserInfos) {
                if (cmsOaDUserImport.getIdentityNumber().equals(info.getIdentityNumber())) {
                    isRepeatIdentity = true;
                    repeatIdentity.append(cmsOaDUserImport.getIdentityNumber()).append("、");
                    break;
                }
            }
            int isArea = 0;
            for (OaSysArea area : areaList) {
                if (cmsOaDUserImport.getDriverCityName().equals(area.getName())) {
                    isArea = 1;
                    break;
                }
            }
            if (isArea == 0) {
                isRepeatArea = true;
            }
            for (OaSysVehicle vehicle : oaSysVehicles) {
                if (cmsOaDUserImport.getVehNo().equals(vehicle.getVehNo())) {
                    isRepeatVehNo = true;
                    repeatVehNo.append(cmsOaDUserImport.getVehNo()).append("、");
                    break;
                }
                if (cmsOaDUserImport.getVehFrameNumber().equals(vehicle.getVehFrameNumber())) {
                    isRepeatVehFrame = true;
                    //repeatVehFrame.append(cmsOaDUserImport.getVehFrameNumber()).append("、");
                    break;
                }
            }
            // 用户放入待插入列表
            OaDUser oaDUser = this.insertOaDUserBean(sysUserId, tag, cmsOaDUserImport.getDriverPhone(), date, cmsOaDUserImport);
            oaDUserList.add(oaDUser);
            // 用户机构关联入待插入列表
            oaDUserOfficeList.add(this.insertOaDUserOffice(oaDUser.getDriverId(), sysUserId, tag, date, cmsOaDUserImport.getOfficeCode(), offices));
            // 用户信息
            oaDUserInfoList.add(this.insertOaDUserInfo(areaList, oaDUser.getDriverId(), sysUserId, tag, clientId, sid, date, cmsOaDUserImport));
            // 用户钱包
            oaDWalletList.add(this.insertOaDWallet(oaDUser.getDriverId(), sysUserId, cmsOaDUserImport.getOfficeCode(), tag, date));
            // 车辆
            oaSysVehiclesList.add(this.insertOaSysVehicle(oaDUser, areaList, dictList, cmsOaDUserImport, sysUserId, tag, date));
        }
        disposeData(cmsOaDUserImportList, repeatPhone, repeatVehNo, repeatVehFrame, repeatIdentity, formatPhone, formatVehNo, formatVehFrame, formatIdentity,
                isRepeatPhone, isRepeatVehNo, isRepeatVehFrame, isRepeatIdentity, isRepeatArea, isFormatPhone, isFormatVehNo, isFormatVehFrame, isFormatIdentity,
                oaDUserInfoList, oaDUserList, oaDWalletList, oaDUserOfficeList, oaSysVehiclesList, tag);
        return EErrorCode.impSuccess.getDesc();
    }

    /**
     * 校验
     */
    public void verify(Map<String, Integer> phoneMap, Map<String, Integer> vehNoMap, Map<String, Integer> vehFrameNumberMap, Map<String, Integer> identityNumberMap, CmsOaDUserImport cmsOaDUserImport) {
        if (CheckUtil.objIsEmpty(cmsOaDUserImport.getDriverPhone(), cmsOaDUserImport.getDriverName(), cmsOaDUserImport.getIdentityNumber(),
                cmsOaDUserImport.getSex(), cmsOaDUserImport.getDriverCityName())) {
            throw PangException.create(EErrorCode.impNull);
        }
        if (CheckUtil.objIsEmpty(cmsOaDUserImport.getVehNo(), cmsOaDUserImport.getDriverCityName(), cmsOaDUserImport.getVehColor(), cmsOaDUserImport.getVehCityName())) {
            throw PangException.create(EErrorCode.impVehicleNull);
        }
        if (phoneMap.containsKey(cmsOaDUserImport.getDriverPhone())) {
            throw PangException.create(EErrorCode.impRepeatPhone);
        }
//        if (vehFrameNumberMap.containsKey(cmsOaDUserImport.getVehFrameNumber())) {
//            throw PangException.create(EErrorCode.impRepeatVehFrame);
//        }
        if (vehNoMap.containsKey(cmsOaDUserImport.getVehNo())) {
            throw PangException.create(EErrorCode.impRepeatVeh);
        }
        if (identityNumberMap.containsKey(cmsOaDUserImport.getIdentityNumber())) {
            throw PangException.create(EErrorCode.impRepeatIDENTITY);
        }
    }

    /**
     * 处理数据
     */
    public void disposeData(List<CmsOaDUserImport> cmsOaDUserImportList, StringBuffer repeatPhone, StringBuffer repeatVehNo, StringBuffer repeatVehFrame, StringBuffer repeatIdentity, StringBuffer formatPhone, StringBuffer formatVehNo, StringBuffer formatVehFrame, StringBuffer formatIdentity,
                            boolean isRepeatPhone, boolean isRepeatVehNo, boolean isRepeatVehFrame, boolean isRepeatIdentity, boolean isRepeatArea, boolean isFormatPhone, boolean isFormatVehNo, boolean isFormatVehFrame, boolean isFormatIdentity,
                            List<OaDUserInfo> oaDUserInfoList, List<OaDUser> oaDUserList, List<OaDWallet> oaDWalletList, List<OaDUserOffice> oaDUserOfficeList, List<OaSysVehicle> vehicleList, String tag) {
        repeatPhone = repeatPhone.deleteCharAt(repeatPhone.length() - 1);
        repeatVehNo = repeatVehNo.deleteCharAt(repeatVehNo.length() - 1);
//      repeatVehFrame = repeatVehFrame.deleteCharAt(repeatVehFrame.length() - 1);
        repeatIdentity = repeatIdentity.deleteCharAt(repeatIdentity.length() - 1);
        formatPhone = formatPhone.deleteCharAt(formatPhone.length() - 1);
        formatVehNo = formatVehNo.deleteCharAt(formatVehNo.length() - 1);
        formatVehFrame = formatVehFrame.deleteCharAt(formatVehFrame.length() - 1);
        formatIdentity = formatIdentity.deleteCharAt(formatIdentity.length() - 1);
        if (isFormatPhone) {
            throw PangException.create(EErrorCode.formatPhone, formatPhone.toString());
        }
        if (isFormatVehNo) {
            throw PangException.create(EErrorCode.formatVehNo, formatVehNo.toString());
        }
//        if (isFormatVehFrame) {
//            throw PangException.create(EErrorCode.formatVehframe, formatVehFrame.toString());
//        }
        if (isFormatIdentity) {
            throw PangException.create(EErrorCode.formatIdentity, formatIdentity.toString());
        }
        if (isRepeatPhone) {
            throw PangException.create(EErrorCode.impDBRepeatPhone, repeatPhone.toString());
        }
        if (isRepeatVehNo) {
            throw PangException.create(EErrorCode.impDBRepeatVehNo, repeatVehNo.toString());
        }
//      if (!isRepeatVehFrame) {
//            throw PangException.create(EErrorCode.impDBRepeatVehFrame, repeatVehFrame.toString());
//        }
        if (isRepeatIdentity) {
            throw PangException.create(EErrorCode.impDBRepeatIDENTITY, repeatIdentity.toString());
        }
        if (isRepeatArea) {
            throw PangException.create(EErrorCode.formatCityName, EErrorCode.formatCityName.getDesc());
        }
//        boolean b = iOaDUserInfoService.saveBatch(oaDUserInfoList);
//        if (!b) {
//            throw PangException.create(EErrorCode.impFailure);
//        }
//        b = iOaDUserService.saveBatch(oaDUserList);
//        if (!b) {
//            throw PangException.create(EErrorCode.impFailure);
//        }
//        b = iOaDWalletService.saveBatch(oaDWalletList);
//        if (!b) {
//            throw PangException.create(EErrorCode.impFailure);
//        }
//        b = this.iOaDUserOfficeService.saveBatch(oaDUserOfficeList);
//        if (!b) {
//            throw PangException.create(EErrorCode.impFailure);
//        }
//        b = this.iOaSysVehicleService.saveBatch(vehicleList);
//        if (!b) {
//            throw PangException.create(EErrorCode.impFailure);
//        }
        //插入用户的所有信息
        for (OaDUser oaDUser:oaDUserList){
            this.addDUser(oaDUser);
        }
        for (OaDUserInfo oaDUserInfo:oaDUserInfoList){
            this.addUserInfo(oaDUserInfo);
        }
        for(OaDWallet oaDWallet:oaDWalletList){
            this.addWallet(oaDWallet);
        }
        for(OaSysVehicle oaSysVehicle:vehicleList){
            this.addVehicleInfo(oaSysVehicle);
        }
        for (OaDUserOffice oaDUserOffice:oaDUserOfficeList){
            this.addOaDUserOffice(oaDUserOffice);
        }
        List<String> vehCode = new ArrayList<>();
        for (CmsOaDUserImport userImport : cmsOaDUserImportList) {
            vehCode.add(userImport.getVehicleModel());
//            Long userId = 0L;
//            Long vehId = 0L;
//            Date date = new Date();
//            Long sysUserId = 0L;
//            for (OaSysVehicle vehicle : vehicleList) {
//                if (userImport.getVehNo().equals(vehicle.getVehNo())) {
//                    vehId = vehicle.getVehicleId();
//                    sysUserId = vehicle.getCreateUser();
//                    break;
//                }
//            }
//            for (OaDUser user : oaDUserList) {
//                if (userImport.getDriverPhone().equals(user.getDriverPhone())) {
//                    userId = user.getDriverId();
//                    date = user.getCreateTime();
//                    break;
//                }
//            }
//            OaDDriverVehicle driverVehicle = new OaDDriverVehicle();
//            driverVehicle.setVehicleId(vehId);
//            driverVehicle.setLinkedId(IDUtil.nextId());
//            driverVehicle.setDriverId(userId);
//            driverVehicle.setCreateTime(date);
//            driverVehicle.setCreateUser(sysUserId);
//            driverVehicle.setUpdateTime(date);
//            driverVehicle.setIsUse(1);
//            driverVehicle.setTag(tag);
//            driverVehicle.setUpdateUser(sysUserId);
//            oaDDriverVehicleMapper.insert(driverVehicle);
        }
        // 修改关联
        QueryWrapper<OaSysVehicleMdict> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(OaSysVehicleMdict.CODE, vehCode);
        List<OaSysVehicleMdict> mdictList = oaSysVehicleMdictMapper.selectList(queryWrapper);
        for (OaSysVehicleMdict mdict : mdictList) {
            mdict.setIsRelation(1);
            mdict.setUpdateTime(new Date());
            oaSysVehicleMdictMapper.updateById(mdict);
        }
    }

    private OaSysVehicle insertOaSysVehicle(OaDUser oaDUser, List<OaSysArea> areaList, List<OaSysDict> dictList, CmsOaDUserImport cmsOaDUserImport, Long sysUserId, String tag, Date date) {
        OaSysVehicle vehicle = new OaSysVehicle();
        Long vehId = IDUtil.nextId();
        vehicle.setVehicleId(vehId);
        vehicle.setVehFrameNumber(cmsOaDUserImport.getVehFrameNumber());
        vehicle.setVehNo(cmsOaDUserImport.getVehNo());
        vehicle.setVehEngineNumber(cmsOaDUserImport.getVehEngineNumber());

        String code = cmsOaDUserImport.getVehicleModel();
        int vehicleType = 0;
        if (CheckUtil.strIsNotEmpty(code)) {
            OaSysVehicleMdict vehicleMdict = oaSysVehicleMdictMapper.selectOne(Qw.create().eq(OaSysVehicleMdict.EXPAND3, code));
            if (vehicleMdict != null) {
                code = vehicleMdict.getCode();
                vehicleType = vehicleMdict.getVehicleType();
            }
        }
        vehicle.setVehType(vehicleType);
        vehicle.setCode(code);
        vehicle.setVehColor(0);
        vehicle.setVehStatus(0);
        for (OaSysArea dict : areaList) {
            if (dict.getName().equals(cmsOaDUserImport.getVehCityName())) {
                vehicle.setCityCode(dict.getAdCode());
                break;
            }
        }
        for (OaSysDict dict : dictList) {
            if (dict.getLabel().equals(cmsOaDUserImport.getVehColor())) {
                vehicle.setVehColor(Integer.valueOf(dict.getValue()));
                break;
            }
        }
        if (cmsOaDUserImport.getVehFuelType().equals(EVehicleType.vehFuelTypeElectric.getDesc())) {
            vehicle.setVehFuelType(EVehicleType.vehFuelTypeElectric.getValue());
        } else if (cmsOaDUserImport.getVehFuelType().equals(EVehicleType.vehFuelTypeTanker.getDesc())) {
            vehicle.setVehFuelType(EVehicleType.vehFuelTypeTanker.getValue());
        } else if (cmsOaDUserImport.getVehFuelType().equals(EVehicleType.vehFuelTypeDiesel.getDesc())) {
            vehicle.setVehFuelType(EVehicleType.vehFuelTypeDiesel.getValue());
        } else if (cmsOaDUserImport.getVehFuelType().equals(EVehicleType.vehFuelTypeHybird.getDesc())) {
            vehicle.setVehFuelType(EVehicleType.vehFuelTypeHybird.getValue());
        } else {
            vehicle.setVehFuelType(EVehicleType.vehFuelTypePlugIn.getValue());
        }
        vehicle.setVehicleOwnerId(oaDUser.getDriverId());
        vehicle.setCreateTime(date);
        vehicle.setCreateUser(sysUserId);
        vehicle.setUpdateTime(date);
        vehicle.setTag(tag);
        vehicle.setUpdateUser(sysUserId);
        return vehicle;
    }

    /**
     * 用户钱包信息 待插入实体
     *
     * @param driverId  用户id
     * @param sysUserId 后台用户id
     * @param officeId  机构id
     * @param tag       租户
     * @param date      当前时间
     * @return
     */
    private OaDWallet insertOaDWallet(Long driverId, Long sysUserId, Long officeId, String tag, Date date) {
        BigDecimal zero = new BigDecimal("0");
        OaDWallet oaDWallet = new OaDWallet();
        oaDWallet.setWalletId(IDUtil.nextId());
        oaDWallet.setDriverId(driverId);
        oaDWallet.setOfficeId(officeId);
        oaDWallet.setWalletBalance(zero);
        oaDWallet.setDeptOfficialBalance(zero);
        oaDWallet.setTag(tag);
        oaDWallet.setCreateUser(sysUserId);
        oaDWallet.setCreateTime(date);
        oaDWallet.setUpdateUser(sysUserId);
        oaDWallet.setUpdateTime(date);
        return oaDWallet;
    }

    /**
     * 用户信息 待插入实体
     *
     * @param driverId         用户id
     * @param sysUserId        后台用户id
     * @param tag              租户
     * @param date             当前时间
     * @param cmsOaDUserImport ex表格数据
     * @return
     */
    private OaDUserInfo insertOaDUserInfo(List<OaSysArea> areaList, Long driverId, Long sysUserId, String tag, String clientId, Long sid, Date date, CmsOaDUserImport cmsOaDUserImport) {
        OaDUserInfo oaDUserInfo = new OaDUserInfo();
        oaDUserInfo.setInfoId(IDUtil.nextId());
        oaDUserInfo.setDriverId(driverId);
        oaDUserInfo.setEmergencyAddress("");
        oaDUserInfo.setDriveLicenseType("");
        oaDUserInfo.setDriverType(EOaDUserDriverType.proprietary.getValue());
        oaDUserInfo.setAddress("");
        oaDUserInfo.setIdentityNumber(cmsOaDUserImport.getIdentityNumber());
        oaDUserInfo.setDriveLicenseNo(cmsOaDUserImport.getIdentityNumber());
        oaDUserInfo.setIdentityType(EOacUserInfoIdentityType.IDCard.getValue());
        oaDUserInfo.setPassingDate(date);
        oaDUserInfo.setEmergencyContact("");
        oaDUserInfo.setCreateUser(sysUserId);
        oaDUserInfo.setCreateTime(date);
        oaDUserInfo.setUpdateUser(sysUserId);
        oaDUserInfo.setEmergencyMobile(cmsOaDUserImport.getEmergencyMobile());
        oaDUserInfo.setAuditType(EOacUserInfoAuditType.manualReview.getValue());
        oaDUserInfo.setAgreement(EOaCUserInfoAgreement.yes.getValue());
        for (OaSysArea area : areaList) {
            if (area.getName().equals(cmsOaDUserImport.getDriverCityName())) {
                oaDUserInfo.setDriverCityId(area.getAdCode());
                oaDUserInfo.setRegisterCityId(Integer.valueOf(area.getAdCode()));
                break;
            }
        }
        oaDUserInfo.setTag(tag);
        oaDUserInfo.setUpdateTime(date);
        oaDUserInfo.setBankAccountName(cmsOaDUserImport.getDriverName());
        oaDUserInfo.setBankAccount(cmsOaDUserImport.getBankAccount());
        oaDUserInfo.setBankName(cmsOaDUserImport.getBankName());
        oaDUserInfo.setOpeningBank(cmsOaDUserImport.getOpeningBank());
        oaDUserInfo.setAlipayAccount(cmsOaDUserImport.getAlipayAccount());
        oaDUserInfo.setAlipayAccountName(cmsOaDUserImport.getAlipayAccountName());
        if (CheckUtil.objIsNotEmpty(sid, driverId, clientId, tag)) {
            AmapTidParam tidParam = new AmapTidParam();
            tidParam.setServiceId(sid.toString());
            tidParam.setUserId(driverId);
            tidParam.setClientId(clientId);
            tidParam.setTag(tag);
            Long tid = amapService.getAmapTid(tidParam);
            if (CheckUtil.objIsNotEmpty(tid)) {
                oaDUserInfo.setTid(tid);
            }
        }
        oaDUserInfo.setIsOrder(ParameterEnum.ZERO.getType());
        oaDUserInfo.setAcceptancOrderStatus(ParameterEnum.ZERO.getType());
        return oaDUserInfo;
    }

    /**
     * 用户机构关联 待插入实体
     *
     * @param driverId
     * @param sysUserId  后台用户id
     * @param tag        租户
     * @param date       当前时间
     * @param officeCode 机构code
     * @return
     */
    private OaDUserOffice insertOaDUserOffice(Long driverId, Long sysUserId, String tag, Date date, Long officeCode, List<OaSysOffice> offices) {
        OaDUserOffice oaDUserOffice = new OaDUserOffice();
        oaDUserOffice.setLinkedId(IDUtil.nextId());
        oaDUserOffice.setDriverId(driverId);
        for (OaSysOffice office : offices) {
            if (officeCode == Long.parseLong(office.getCode())) {
                oaDUserOffice.setOfficeId(office.getOfficeId());
                //修改供应商的司机数量
                OaSysUser manager = oaSysUserMapper.selectOne(Qw.create().eq(OaSysUser.OFFICE_ID, office.getOfficeId()));
                manager.setExpand4(manager.getExpand4() + 1);
                oaSysUserMapper.updateById(manager);
                break;
            }
        }
        if (CheckUtil.objIsEmpty(oaDUserOffice.getOfficeId())) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("<p>").append(EErrorCode.unOfficeCode.getDesc()).append(":</p>");
            stringBuffer.append("<p>").append(officeCode).append("</p>");
            throw PangException.create(EErrorCode.unOfficeCode, stringBuffer.toString());
        }
        oaDUserOffice.setTag(tag);
        oaDUserOffice.setCreateUser(sysUserId);
        oaDUserOffice.setCreateTime(date);
        oaDUserOffice.setUpdateUser(sysUserId);
        oaDUserOffice.setUpdateTime(date);
        return oaDUserOffice;
    }

    /**
     * 用户待插入实体
     *
     * @param sysUserId        后台用户id
     * @param tag              租户
     * @param userPhone        用户手机号
     * @param date             当前时间
     * @param cmsOaDUserImport ex表格数据
     * @return
     */
    private OaDUser insertOaDUserBean(Long sysUserId, String tag, String userPhone, Date date, CmsOaDUserImport cmsOaDUserImport) {
        OaDUser oaDUser = new OaDUser();
        oaDUser.setDriverId(IDUtil.nextId());
        oaDUser.setDriverPhone(userPhone);
        oaDUser.setLoginAccount(userPhone);
        oaDUser.setTag(tag);
        oaDUser.setCreateUser(sysUserId);
        oaDUser.setCreateTime(date);
        oaDUser.setUpdateUser(sysUserId);
        oaDUser.setUpdateTime(date);
        oaDUser.setDriverName(cmsOaDUserImport.getDriverName());
        oaDUser.setSex(EOaCUserSex.findByDesc(cmsOaDUserImport.getSex()).getValue());
        oaDUser.setEmailStatus(EOaCUserEmailStatus.no.getValue());
        oaDUser.setEmail("");
        oaDUser.setIdentityVerfied(EOaCUserIdentityVerfied.examinationPassed.getValue());
        oaDUser.setIsBlocked(EOaCUserIsBlocked.normal.getValue());
        oaDUser.setAccountStatus(ParameterEnum.ZERO.getType());
        return oaDUser;
    }

    private void addDUser(OaDUser newOaDUser) {
        OaDUser oaDUser = new OaDUser();
        oaDUser.setDriverId(newOaDUser.getDriverId());
        oaDUser.setDriverPhone(newOaDUser.getDriverPhone());
        oaDUser.setLoginAccount(newOaDUser.getDriverPhone());
        oaDUser.setDriverName(newOaDUser.getDriverName());
        oaDUser.setSex(newOaDUser.getSex());
        oaDUser.setTag(TokenUtil.getTag());//TokenUtil.getTag()
        oaDUser.setCreateUser(TokenUtil.getTokenUserId());//TokenUtil.getTokenUserId()
        oaDUser.setCreateTime(new Date());
        oaDUser.setUpdateTime(new Date());
        oaDUser.setAccountStatus(0);
        int insert = oaDUserMapper.insert(oaDUser);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 添加司机信息表
     *
     */
    private void addUserInfo(OaDUserInfo newOaDUserInfo) {
        OaDUserInfo oaDUserInfo = new OaDUserInfo();
        oaDUserInfo.setInfoId(IDUtil.nextId());
        oaDUserInfo.setDriverId(newOaDUserInfo.getDriverId());
        oaDUserInfo.setIdentityNumber(newOaDUserInfo.getIdentityNumber());
        oaDUserInfo.setPassingDate(new Date());
        oaDUserInfo.setAuditType(0);
        oaDUserInfo.setRegisterCityId(newOaDUserInfo.getRegisterCityId());
        oaDUserInfo.setDriverType(2);
        oaDUserInfo.setAgreement(1);
        oaDUserInfo.setTotalServiceScore(100);
        oaDUserInfo.setBeenDriving(newOaDUserInfo.getBeenDriving());
        oaDUserInfo.setOrderQuantityCompleted(0);
        oaDUserInfo.setTag(TokenUtil.getTag());//TokenUtil.getTag()
        oaDUserInfo.setCreateUser(TokenUtil.getTokenUserId());//TokenUtil.getTokenUserId()
        oaDUserInfo.setCreateTime(new Date());
        oaDUserInfo.setUpdateTime(new Date());
        oaDUserInfo.setDriverCityId(newOaDUserInfo.getDriverCityId());
        List<OaSysGlobalConfig> oaSysGlobalConfigs = oaSysGlobalConfigMapper.selectList(Wrappers.<OaSysGlobalConfig>lambdaQuery().eq(OaSysGlobalConfig::getTag, TokenUtil.getTag()));
        if (oaSysGlobalConfigs.size() == 1) {
            if (CheckUtil.objIsNotEmpty(oaSysGlobalConfigs.get(0).getGouldServiceId())) {
                AmapTidParam amapTidParam = new AmapTidParam();
                amapTidParam.setClientId(TokenUtil.getClientId());
                amapTidParam.setServiceId(oaSysGlobalConfigs.get(0).getGouldServiceId().toString());
                amapTidParam.setTag(TokenUtil.getTag());
                amapTidParam.setUserId(newOaDUserInfo.getDriverId());
                Long sid = iAmapService.getAmapTid(amapTidParam);
                oaDUserInfo.setTid(sid);
            }
        }
        int insert = oaDUserInfoMapper.insert(oaDUserInfo);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 插入钱包的信息
     *
     */
    private void addWallet(OaDWallet newOaDWallet) {
        UserLoginResult userLoginResult = (UserLoginResult) TokenUtil.getTokenUserEntity(UserLoginResult.class);
        OaDWallet oaDWallet = new OaDWallet();
        oaDWallet.setWalletId(IDUtil.nextId());
        oaDWallet.setDriverId(newOaDWallet.getDriverId());
        oaDWallet.setOfficeId(userLoginResult.getOfficeId());
        oaDWallet.setTag(TokenUtil.getTag());//TokenUtil.getTag()
        oaDWallet.setCreateUser(TokenUtil.getTokenUserId());//TokenUtil.getTokenUserId()
        oaDWallet.setCreateTime(new Date());
        oaDWallet.setUpdateTime(new Date());
        int insert = oaDWalletMapper.insert(oaDWallet);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 添加车辆信息
     *
     */
    private void addVehicleInfo(OaSysVehicle newOaSysVehicle) {
        long nextId = IDUtil.nextId();
        OaSysVehicle oaSysVehicle = new OaSysVehicle();
        oaSysVehicle.setVehicleId(nextId);
        oaSysVehicle.setVehNo(newOaSysVehicle.getVehNo());
        oaSysVehicle.setVehStatus(0);
        oaSysVehicle.setVehColor(newOaSysVehicle.getVehColor());
        oaSysVehicle.setCode(newOaSysVehicle.getCode());
        oaSysVehicle.setVehFuelType(newOaSysVehicle.getVehFuelType());
        oaSysVehicle.setTag(TokenUtil.getTag());//TokenUtil.getTag()
        oaSysVehicle.setCreateUser(TokenUtil.getTokenUserId());//TokenUtil.getTokenUserId()
        oaSysVehicle.setCreateTime(new Date());
        oaSysVehicle.setUpdateTime(new Date());
        oaSysVehicle.setCityCode(newOaSysVehicle.getCityCode());
        oaSysVehicle.setVehicleOwnerId(newOaSysVehicle.getVehicleOwnerId());
        oaSysVehicle.setVehType(newOaSysVehicle.getVehType());
        int insert = oaSysVehicleMapper.insert(oaSysVehicle);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
        this.addDriverVehicle(newOaSysVehicle.getVehicleOwnerId(), nextId);

    }

    /**
     * 添加司机车辆关联信息
     *
     * @param driverId
     */
    private void addDriverVehicle(Long driverId, Long vehicleId) {
        OaDDriverVehicle oaDDriverVehicle = new OaDDriverVehicle();
        oaDDriverVehicle.setLinkedId(IDUtil.nextId());
        oaDDriverVehicle.setDriverId(driverId);
        oaDDriverVehicle.setVehicleId(vehicleId);
        oaDDriverVehicle.setIsUse(1);
        oaDDriverVehicle.setTag(TokenUtil.getTag());//TokenUtil.getTag()
        oaDDriverVehicle.setCreateUser(TokenUtil.getTokenUserId());//TokenUtil.getTokenUserId()
        oaDDriverVehicle.setCreateTime(new Date());
        oaDDriverVehicle.setUpdateTime(new Date());
        int insert = oaDDriverVehicleMapper.insert(oaDDriverVehicle);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }

    /**
     * 添加机构
     */
    private void addOaDUserOffice(OaDUserOffice newOaDUserOffice) {

        OaDUserOffice oaDUserOffice = new OaDUserOffice();
        oaDUserOffice.setLinkedId(IDUtil.nextId());
        oaDUserOffice.setDriverId(newOaDUserOffice.getDriverId());
        oaDUserOffice.setOfficeId(newOaDUserOffice.getOfficeId());
        oaDUserOffice.setTag(TokenUtil.getTag());//TokenUtil.getTag()
        oaDUserOffice.setCreateUser(TokenUtil.getTokenUserId());//TokenUtil.getTokenUserId()
        oaDUserOffice.setCreateTime(new Date());
        oaDUserOffice.setUpdateTime(new Date());
        int insert = oaDUserOfficeMapper.insert(oaDUserOffice);
        if (insert == 0) {
            throw PangException.create(EErrorCode.addError);
        }
    }
}
